package hn.sigit.dao.hnd.special;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import hn.sigit.dao.SigitDAO;
import hn.sigit.model.hnd.special.HND_Counter;
import hn.sigit.model.hnd.special.HND_CounterType;

public class HND_CounterDAO extends SigitDAO<HND_Counter> {
	private static final long serialVersionUID = -4000085757396192412L;

	protected HND_CounterDAO() {	
	}
	
	public synchronized static Long nextValue(HND_CounterType counterType) {
		return nextValue(getSession(), counterType);
	}
	
	public synchronized static Long nextValue(Session session, HND_CounterType counterType) {
		Criteria criteria = session.createCriteria(HND_Counter.class);
		criteria.add(Restrictions.eq("type", counterType));
		
		HND_Counter hndCounter = (HND_Counter) criteria.uniqueResult();
		if (hndCounter == null) {
			hndCounter = new HND_Counter();
			hndCounter.setType(counterType);
			hndCounter.setCount(50001);
		}
		else {
			hndCounter.setCount(hndCounter.getCount() + 1);
		}
		
		save(hndCounter);
		
		return hndCounter.getCount();
	}
}
